package com.tanhua.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import model.domain.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (!JwtUtils.verifyToken(token)) {
            response.setStatus(401);
            return false;
        }
        Claims claims = JwtUtils.getClaims(token);
        UserHolder.set(new User() {{
                setId(Long.valueOf((Integer) claims.get("id")));
                setMobile((String) claims.get("mobile"));
            }});
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
